const mongoose = require('mongoose')
const handleE11000 = require('../common/error-handle.api').handleE11000
const Schema = mongoose.Schema

const ClientSchema = new Schema({
  _id: { type: String, required: true }, // _id默认就会给index: 1, 如果重复定义unique: true会出错
  name: { type: String, required: true },
  company: { type: String, required: true }
}, {
  versionKey: false,
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
})

// middleware
ClientSchema.post('save', handleE11000)
ClientSchema.post('update', handleE11000)
ClientSchema.post('findOneAndUpdate', handleE11000)
ClientSchema.post('insertMany', handleE11000)

const Client = mongoose.model('Client', ClientSchema)

exports = module.exports = Client
